<template>
  <el-card>
    <el-button
      v-permission="'btn.Trademark.add'"
      @click="addTrademark"
      type="primary"
      icon="Plus"
    >
      添加品牌
    </el-button>
    <!-- 
      el-table 表单组件用于渲染页面数据,
        :data 表示渲染的数据,但我们绑定数据时,el-table-column中的每一列可以通过prop选择要渲染的每一列数据

        el-table-column
          type: 可以选择当前table列的类型,例如index序号展示,select选择框展示;
          label: 每一列的提示,在表头中展示
          prop: 要进行展示的数据,当直接使用prop时,表格中会在div标签中展示
    -->
    <el-table :data="tableData" height="400" border style="margin: 15px 0">
      <el-table-column type="index" label="序号" width="80" align="center" />
      <el-table-column prop="tmName" label="品牌名称" width="180" />
      <el-table-column prop="address" label="品牌Logo" align="center">
        <template #default="{ row }">
          <el-image
            style="width: 50px; height: 50px"
            :src="row.logoUrl"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="品牌操作" align="center">
        <template #default="{ row }">
          <el-button
            type="primary"
            size="small"
            icon="Edit"
            @click="editTreadMark(row)"
            v-permission="'btn.Trademark.update'"
          ></el-button>
          <el-popconfirm
            :title="`确定要删除${row.tmName}吗?`"
            icon-color="#626e4e"
            icon="Delete"
            width="260"
            @confirm="deleteTreadMark(row.id)"
          >
            <template #reference>
              <el-button
                v-permission="'btn.Trademark.remove'"
                type="danger"
                size="small"
                icon="Delete"
              ></el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      v-model:current-page="pageNo"
      v-model:page-size="limit"
      :page-sizes="[3, 5, 10, 15]"
      layout=" prev, pager, next, jumper,->,sizes,total"
      :total="total"
      @size-change="changeSize"
      @current-change="getTrademarkRequest"
    />
  </el-card>
  <el-dialog
    v-model="dialogVisible"
    :title="addOrUpdateTrademark.id ? '编辑品牌' : '添加品牌'"
    width="40%"
  >
    <el-form
      ref="formRef"
      :model="addOrUpdateTrademark"
      :rules="rules"
      label-position="right"
      label-width="100px"
      style="max-width: 460px"
    >
      <el-form-item label="品牌名称" prop="tmName">
        <el-input
          v-model="addOrUpdateTrademark.tmName"
          placeholder="请输入品牌名称"
        />
      </el-form-item>
      <el-form-item label="品牌Logo" prop="logoUrl">
        <el-upload
          :before-upload="beforeAvatarUpload"
          :on-success="handleAvatarSuccess"
          :show-file-list="false"
          class="avatar-uploader"
          action="/api/admin/product/fileUpload"
        >
          <img
            v-if="addOrUpdateTrademark.logoUrl"
            :src="addOrUpdateTrademark.logoUrl"
            class="avatar"
          />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateTrademarkData">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ElMessage } from 'element-plus'
import {
  getTrademarkList,
  updateTrademark,
  deleteTrademark,
} from '@/api/product/trademark'
// 引入upload组件中type类型
import type { UploadProps } from 'element-plus'
// 引入自己定义的type类型
import type {
  TradeMarkResponseData,
  TradeMark,
} from '@/api/product/trademark/type'
import { onMounted, reactive, ref } from 'vue'

const tableData = ref<any>([])
let pageNo = ref<number>(1)
let limit = ref<number>(5)
let total = ref<number>(0)
let formRef = ref()
// dialog展示框内容
const dialogVisible = ref<boolean>(false)
// 手机dialog中form表单数据
let addOrUpdateTrademark = reactive<TradeMark>({
  tmName: '',
  logoUrl: '',
  id: null,
})
// 表单校验
const validateTmName = (rule: any, value: any, callBack: any) => {
  if (value.trim().length > 3) {
    callBack()
  } else {
    callBack(new Error('品牌名称不得小于三位'))
  }
}
const validateLogoUrl = (rule: any, value: any, cb: any) => {
  if (!value) {
    cb(new Error(' 请选择上传图片'))
  } else {
    cb()
  }
}
const rules = {
  tmName: [{ required: true, validator: validateTmName, trigger: 'blur' }],
  logoUrl: [{ required: true, validator: validateLogoUrl, trigger: 'blur' }],
}

// 上传头像之前的回调
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (
    rawFile.type == 'image/jpeg' ||
    rawFile.type == 'image/png' ||
    rawFile.type == 'image/gif'
  ) {
    if (rawFile.size / 1024 / 1024 > 4) {
      ElMessage.error('请上传低于4M的图片')
      return false
    }
    return true
  } else {
    ElMessage.error('请上传以png,jpeg,gif类型图片')
  }
}
// 上传头像之后的回调
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile,
) => {
  formRef.value?.clearValidate('logoUrl')
  addOrUpdateTrademark.logoUrl = response.data
}
// 点击dialog中确定按钮
const updateTrademarkData = async () => {
  await formRef.value.validate()
  const res = await updateTrademark(addOrUpdateTrademark)
  if (res.code === 200) {
    ElMessage.success(addOrUpdateTrademark.id ? '修改品牌成功' : '添加品牌成功')
    getTrademarkRequest(addOrUpdateTrademark.id ? pageNo.value : 1)
  } else {
    ElMessage.error('操作失败,请重试')
  }
  dialogVisible.value = false
}

onMounted(() => {
  getTrademarkRequest()
})
const getTrademarkRequest = async (pager = 1) => {
  pageNo.value = pager
  const res: TradeMarkResponseData = await getTrademarkList(
    pageNo.value,
    limit.value,
  )
  tableData.value = res.data.records
  total.value = res.data.total
}

// 修改每页展示条数
const changeSize = () => {
  getTrademarkRequest()
}

// 删除品牌
const deleteTreadMark = async (id: any) => {
  const res = await deleteTrademark(id)
  if (res.code === 200) {
    ElMessage.success('删除成功')
    // 当前页只剩一条数据时,直接请求上一页的数据,可以减少一次请求
    getTrademarkRequest(
      tableData.value.length > 1 ? pageNo.value : pageNo.value - 1,
    )
  }
}
// 编辑品牌
const editTreadMark = (row: any) => {
  formRef.value?.clearValidate()
  addOrUpdateTrademark.id = row.id
  addOrUpdateTrademark.tmName = row.tmName
  addOrUpdateTrademark.logoUrl = row.logoUrl
  dialogVisible.value = true
}
// 添加品牌
const addTrademark = () => {
  formRef.value?.clearValidate()
  addOrUpdateTrademark.tmName = ''
  addOrUpdateTrademark.logoUrl = ''
  addOrUpdateTrademark.id = null
  dialogVisible.value = true
}
</script>

<style lang="scss" scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
